<?php
/**
 * shell脚本逻辑
 */

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Tools\GooglePay;
use App\Tools\FunTool;
use App\Tools\Af;
use App\Datas\Pay;
use App\Datas\User;
use App\Datas\UserDrawing;
use App\Datas\System;
use App\Datas\EventList;
use App\Datas\UserOntrial;

class GoogleShell
{
    
    /**
     * google 的未支付单
     */
    public static function checkGoogleOrder(){

        $list = DB::table("pay_order")
                  ->where('client_notify', 1)
                  ->where('is_repair',2)
                  ->where('platform', 2)//安卓google支付的
                  ->where('status',0)
                  ->limit(5)
                  ->get()->toArray();
        if (count($list) <=0) {
            echo '暂无数据要处理'.PHP_EOL;
            exit;
        }

        foreach ($list as $key => $value) {
            if ( !empty($value->external_order_id) || $value->status == 1 ) {//已经回调或者更改过来的
                continue;
            }
            if (empty($value->extend)) {//没有支付信息的
                continue;
            }
            if ($value->google_is_subscribe == 1) {//谷歌订阅的
                self::dealGoogleSubscribe($value->extend, $value->id);
                
            }else{//正常购买商品的
                self::dealGooglePurchase($value->extend, $value->id);
            }
        }

        echo '处理完毕'.PHP_EOL;
        exit;

    }


    /**
     * 处理google购买商品逻辑和后续业务处理
     */
    public static function dealGooglePurchase($data, $id){

        try{

            $data = json_decode($data, true);

            $externalOrderId = $data['orderId'];

            $result = GooglePay::getGooglePurchaseOrderInfo($data['order_id'], $data['productId'], $data['purchaseToken']);
            if ( isset($result) && $result->purchaseState == 0) {//支付成功

                $res = self::doGooglePayBusiness($result);
                DB::table('pay_order')->where('id',$id)->update(['remark'=>$res['msg'], 'is_repair'=>1]);
                
            }else{
                DB::table('pay_order')->where('id',$id)->update(['remark'=>json_encode($result), 'is_repair'=>1, 'status'=>2, 'external_order_id'=>$data['orderId']]);
            }

        }catch(\Exception $e){
            DB::table('pay_order')->where('id',$id)->update(['remark'=>'无效：'.json_encode($e->getMessage()), 'is_repair'=>1, 'status'=>3, 'external_order_id'=>$data['orderId']]);
        }

    }

     /**
     * 处理google订阅支付逻辑和后续业务处理
     */
    public static function dealGoogleSubscribe($data, $id){


        try{

            $data = json_decode($data, true);

            $result = GooglePay::getGoogleSubscribeOrderInfo($data['order_id'], $data['purchaseToken']);

            if ( isset($result) && $data['purchaseState'] == 0 ) {//订阅成功

                if ($result->subscriptionState == 'SUBSCRIPTION_STATE_ACTIVE') {//有效期间
                    $res = self::doGoogleSubscribeBusiness($result, $data);
                    DB::table('pay_order')->where('id',$id)->update(['remark'=>$res['msg'], 'is_repair'=>1]);
                }
                if ($result->subscriptionState == 'SUBSCRIPTION_STATE_CANCELED') {//退款/取消
                    DB::table('pay_order')->where('id',$id)->update(['remark'=>json_encode($result), 'is_repair'=>1, 'status'=>2, 'external_order_id'=>$data['orderId']]);
                }
                if ($result->subscriptionState == 'SUBSCRIPTION_STATE_EXPIRED') {//过期
                    DB::table('pay_order')->where('id',$id)->update(['remark'=>json_encode($result), 'is_repair'=>1, 'status'=>3, 'external_order_id'=>$data['orderId']]);
                }
                
            }else{
                DB::table('pay_order')->where('id',$id)->update(['remark'=>json_encode($result), 'is_repair'=>1, 'status'=>2]);
            }

        }catch(\Exception $e){
            DB::table('pay_order')->where('id',$id)->update(['remark'=>'无效：'.json_encode($e->getMessage()), 'is_repair'=>1, 'status'=>3, 'external_order_id'=>$data['orderId']]);
        }


    }

    /**
     * 处理google购买逻辑和后续业务处理
     */
    public static function doGooglePayBusiness($payOrderInfo) {

        $dataPay = new Pay();

        $orderInfo = $dataPay->getOrder($payOrderInfo->obfuscatedExternalProfileId);
        if ($orderInfo['status'] != 0  || !empty($orderInfo['external_order_id'])) {
            return ['code'=>500, 'msg'=>'支付状态和数据已更改，停止进行。。。'];
        }
        $isSuperVip = false;
        $externalOrderId = $payOrderInfo->orderId;

        DB::beginTransaction();
        try {
            $id = $orderInfo['id'];
            if ($payOrderInfo->quantity > 1) {
                $orderInfo["price"] = $orderInfo["price"] * $payOrderInfo->quantity;
                $orderInfo["dot"] = $orderInfo["dot"] * $payOrderInfo->quantity;
                $dataPay->updatePayById($id,[
                    "price" => $orderInfo["price"],
                    "dot" => $orderInfo["dot"]
                ]);
            }
            $dataPay->updatePay($id, $externalOrderId);

            $userDrawing = new UserDrawing();
            $dataUser = new User();
            //兼容无登录付费
            if($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                $dataUser->updateDot($orderInfo['user_id'], $orderInfo['dot'], 4);
            }
            if (version_compare($orderInfo['version'],  env('NEW_VERSION')) >= 0) {
                //兼容无登录付费
                if($orderInfo['len'] > 0 && $orderInfo['len'] != 36500 && $orderInfo["user_id"] > 0) {
                    if ($orderInfo['is_gold'] == 1) {
                        //续费黄金会员的时间
                        $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len'] * 24 * 3600, 'vip_exp');
                    } else {
                        //续费普通画板的时间
                        $userDrawing->updateUserDrawExp($orderInfo['user_id'], $orderInfo['drawing_id'], $orderInfo['len'] * 24 * 3600);
                    }
                }
            } else {
                if($orderInfo['len'] > 0) {
                    $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len']*24*3600, 'vip_exp');
                }
                if($orderInfo['ecy_len'] > 0) {
                    $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['ecy_len']*24*3600, 'rcy_vip_exp');
                }
            }

            // 更新终生会员
            $isSuperVip = $orderInfo["google_id"] == "lifetime_pro" ? true : false;// 是否是终生会员
            if ($isSuperVip && $orderInfo["user_id"] > 0) {
                $dataUser->updateById($orderInfo['user_id'],["is_super_vip" => 1]);
            }
            //兼容无登录付费
            if ($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                //设置充值赠送点数动画值
                $dataUser->setDhNum($orderInfo['user_id'], $orderInfo['dot']);
            }
            $dataPay->updatePayById($id, ['status'=>1, 'pay_at'=>FunTool::getReduceTime(4)]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return ['code'=>500, 'msg'=>json_encode(["error" => $e->getMessage(),"line" => $e->getLine()])];
        }
        $guid = $orderInfo['device_id'];
        if (empty($guid)) {
            return ['code'=>500, 'msg'=>'device_id为空，不进行上报AF'];
        }
        $systemData = new System();
        $deviceInfo = $systemData->getDevice($guid);
        /*上报订阅数据到AF 开始*/
        $appid = FunTool::getAfAppidByPf($orderInfo['platform']);
        $af = new Af();
        $_aExt = ['line'=>__LINE__, 'in' => 'isGoogleCheckPayBusiness', 'order' => $orderInfo, 'externalOrderId' => $externalOrderId];
        $af->payEvent($deviceInfo['appsfly_id'],$appid,$orderInfo['price'], $_aExt);
        //@todo eks 购买终身会员事件上报
        if(true === $isSuperVip){
            EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");
        }
        /*上报订阅数据到AF 结束*/

        return ['code'=>200, 'msg'=>'成功'];
    }

    /**
     * 处理google订阅逻辑和后续业务处理
     */
    public static function doGoogleSubscribeBusiness($payOrderInfo, $data){

        $dataPay = new Pay();
        $dataUserOntrial = new UserOntrial();
        $dataUser = new User();

        $orderId = $data['order_id'];
        $productId = $data['productId'];

        $orderInfo = $dataPay->getOrder($orderId);
        if ($orderInfo['status'] == 1  || !empty($orderInfo['external_order_id'])) {
            return ['code'=>500, 'msg'=>'支付状态和数据已更改，停止进行。。。'];
        }
        $isTry = false;
        $addUserVip = true;
        $isSubNotify = true;
        $isPayNotify = true;
        //可参考orderInfo中的label，目前只考虑新订阅的
        DB::beginTransaction();
        try{
            $offerId = $payOrderInfo['lineItems'][0]->offerDetails['offerId'];
            if ($productId == 'weekly_pro') {
                //周订阅试用
                if ($offerId == "free-weekly-3") {
                    // 试用的已打标记的，就不处理了
                    if ($orderInfo["status"] == 0 && $orderInfo["is_try"] == 1) {
                        return ['code'=>200,'msg'=>'试用的，暂不处理'];
                    }
                    if (version_compare($orderInfo['version'],  "1.5.0") >= 0) {
                        $orderInfo['len'] = 3;
                        $insertData['exper_time'] = $orderInfo['len']*24*3600 + time();
                        $insertData['exper_product'] = $payOrderInfo['lineItems'][0]->offerDetails['basePlanId'];
                        $insertData['user_id'] = $orderInfo['user_id'];
                        $insertData['created_at'] = time();
                        $insertData['device_id'] = $orderInfo['device_id'];
                        $dataUserOntrial->createData($insertData);
                    }
                    //订阅
                    $isSubNotify = true;
                    //适用订单打个标记
                    $isTry = true;
                } else {
                    // 订阅已成功的就不处理了
                    if ($orderInfo["status"] == 1) {
                        return ['code'=>200,'msg'=>'支付状态已经处理完了，暂不处理'];
                    }
                    //订阅
                    //支付
                    //更新订单号
                    $isSubNotify = true;
                    $isPayNotify = true;
                    $dataPay->newUpdatePay($orderInfo['id'],[
                        'external_order_id'=> $data['orderId'],
                        'label' => "2",
                        "region" => $payOrderInfo->regionCode,
                        "pay_at" => FunTool::getReduceTime(4),
                        "status" => 1
                    ]);
                }

            }else{
                //订阅
                //支付
                //更新订单号
                $isSubNotify = true;
                $isPayNotify = true;
                $dataPay->newUpdatePay($orderInfo['id'],[
                    'external_order_id'=> $data['orderId'],
                    'label' => "3",
                    "region" => $payOrderInfo->regionCode,
                    "pay_at" => FunTool::getReduceTime(4),
                    "status" => 1
                ]);
            }

            if ($isTry) {
                $dataPay->updatePayById($orderInfo['id'],[
                    "is_try" => 1,
                ]);
            }
            if ($addUserVip) {
                if (version_compare($orderInfo['version'],  "1.4.0") >= 0) {
                    //兼容无登录付费
                    if ($orderInfo["user_id"] > 0 ) {
                        $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len'] * 24 * 3600, 'vip_exp');
                    }
                } else {
                    if($orderInfo['len'] > 0 && $orderInfo['ecy_len'] > 0) {
                        $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len']*24*3600, 'vip_exp');
                        $dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['ecy_len']*24*3600, 'rcy_vip_exp');
                    }
                }

                //兼容无登录付费
                if($orderInfo['dot'] > 0 && $orderInfo["user_id"] > 0) {
                    $dataUser->updateDot($orderInfo['user_id'], $orderInfo['dot'], 4);
                }
                //兼容无登录付费
                if ($orderInfo['len'] > 0 && $orderInfo['ecy_len'] > 0 && $orderInfo['dot'] > 0 && $orderInfo["user_id"] > 0) {
                    //设置充值赠送点数动画值
                    $dataUser->setDhNum($orderInfo['user_id'], $orderInfo['dot']);
                }
            }
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>500, 'msg'=>json_encode(["error" => $e->getMessage(),"line" => $e->getLine()])];
        }
        /*上报订阅数据到AF 开始*/
        $guid = $orderInfo['device_id'];
        if (empty($guid)) {
            return ['code'=>500, 'msg'=>'device_id为空，不进行上报AF'];
        }
        $systemData = new System();
        $deviceInfo = $systemData->getDevice($guid);
        $appid = FunTool::getAfAppidByPf($orderInfo['platform']);
        $af = new Af();
        if ($isSubNotify) {
            $_aExt = ['line'=>__LINE__, 'in' => 'isShellCheckSub', 'order' => $orderInfo, 'google_data' => $data];
            $af->subscribeEvent($deviceInfo['appsfly_id'],$appid,$_aExt);
            EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");
        }
        if ($isPayNotify) {
            $_aExt = ['line'=>__LINE__, 'in' => 'isShellCheckPay', 'order' => $orderInfo, 'google_data' => $data];
            $af->payEvent($deviceInfo['appsfly_id'], $appid, $orderInfo["price"], $_aExt);
            EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_renew");
        }
        return ['code'=>200, 'msg'=>'处理成功'];


    }

    


    
}